package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import entity.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.List;

/**
 * @author Macross
 * @Type SpitService.java
 * @Desc 吐槽Service服务类
 * @date 2019/12/18 14:44
 */
@Service
public class SpitService {

    @Autowired
    private SpitDao spitDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 获取所有的吐槽信息列表[无分页处理]
     * @return
     */
    public List<Spit> findAll() {
        return spitDao.findAll();
    }

    /**
     * 获取指定id的吐槽信息
     * @param spitId 吐槽信息id
     * @return
     */
    public Spit findById(String spitId) {
        return spitDao.findById(spitId).orElse(null);
    }

    /**
     * 获取所有的吐槽信息[分页处理]
     *
     * @param spit
     * @param page 分页页码
     * @param size 分页大小
     * @return
     */
    public PageResult<Spit> search(Spit spit, Integer page, Integer size) {
        //分页查询
        Page<Spit> spits = spitDao.findAll(PageRequest.of(page-1, size));
        //封装并返回结果
        return new PageResult<>(spits.getTotalElements(),spits.getContent());
    }

    /**
     * 根据上级ID查询吐槽信息
     * @param parentId 上级ID
     * @param page 分页页码
     * @param size 分页大小
     * @return
     */
    public PageResult<Spit> findByParentId(String parentId, Integer page, Integer size) {
        //分页查询
        Page<Spit> spits = spitDao.findByParentid(parentId, PageRequest.of(page - 1, size));
        //封装并返回结果
        return new PageResult<>(spits.getTotalElements(),spits.getContent());
    }

    /**
     * 添加吐槽
     * @param spit 吐槽信息
     */
    public void add(Spit spit) {
        //设置id
        spit.set_id(idWorker.nextId()+"");
        //保存吐槽信息
        spitDao.save(spit);
    }

    /**
     * 更新吐槽
     * @param spit 吐槽信息
     */
    public void update(Spit spit) {
        spitDao.save(spit);
    }

    /**
     * 删除吐槽
     * @param spitId 吐槽信息ID
     */
    public void delete(String spitId) {
        spitDao.deleteById(spitId);
    }

    /**
     * 吐槽点赞
     * @param spitId 吐槽信息ID
     */
    public void thumbup(String spitId) {
        //创建查询对象
        Query query = new Query();
        //添加查询条件,条件为_id等于指定的spitId
        query.addCriteria(Criteria.where("_id").is(spitId));
        //创建更新对象
        Update update = new Update();
        //点赞数+1
        update.inc("thumbup",1);
        //更新吐槽信息
        mongoTemplate.updateFirst(query,update,"spit");
    }
}
